package com.sumainfor.zuul.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.RRException;
import com.sumainfor.zuul.dao.SysRoleDeptDao;
import com.sumainfor.zuul.entity.SysRoleDeptEntity;
import com.sumainfor.zuul.service.SysRoleDeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 角色与部门对应关系
 */
@Service("sysRoleDeptService")
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptDao, SysRoleDeptEntity> implements SysRoleDeptService {

    /**
     * 根据角色的ID 获取所有的绑定部门的ID列表
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> selectDeptIdList(Integer roleId) {
        return baseMapper.queryDeptIdList(new Integer[]{roleId});
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Integer roleId, List<Integer> deptIdList) {
        //先删除角色与部门关系
        deleteBatch(new Integer[]{roleId});

        if (deptIdList.size() == 0) {
            return;
        }

        //保存角色与菜单关系
        List<SysRoleDeptEntity> list = new ArrayList<>(deptIdList.size());
        for (Integer deptId : deptIdList) {
            SysRoleDeptEntity sysRoleDeptEntity = new SysRoleDeptEntity();
            sysRoleDeptEntity.setDeptId(deptId);
            sysRoleDeptEntity.setRoleId(roleId);

            list.add(sysRoleDeptEntity);
        }
        boolean state = this.insertBatch(list);

        if (state == false) {
            throw new RRException(JsonResult.actionFailure().getErrorMessage());
        }
    }

    @Override
    public List<Integer> queryDeptIdList(Integer[] roleIds) {
        return baseMapper.queryDeptIdList(roleIds);
    }

    @Override
    public int deleteBatch(Integer[] roleIds) {
        return baseMapper.deleteBatch(roleIds);
    }
}
